<template>
  <div class="three-wrapper">
    <div class="box" ref="box"></div>
    <div class="actions"></div>
    <div v-if="tooltip.visible" class="tooltip" :style="tooltipStyle">
      {{ tooltip.content }}
    </div>
  </div>
</template>

<script>
import * as d3 from 'd3'
import axios from 'axios'
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'

const clock = new THREE.Clock()
const FPS = 30
const renderT = 1 / FPS
let timeS = 0

export default {
  components: {},
  props: {},
  data() {
    return {
      el: null,
      scene: null,
      camera: null,
      renderer: null,
      controls: null,
      animationFrameId: null,
      projection: null,
      tooltip: {
        visible: false,
        content: '',
        x: 0,
        y: 0
      },
      raycaster: null,
      mouse: null,
      mapMeshes: [], // 存储所有地图网格对象
      extrudeOptions: {
        depth: -2,
        steps: 10,
        bevelEnabled: true,
        bevelThickness: 0,
        bevelSize: 0,
        bebelSegments: 0,
        curveSegments: 0
      }
    }
  },
  computed: {
    tooltipStyle() {
      return {
        left: this.tooltip.x + 10 + 'px',
        top: this.tooltip.y + 10 + 'px'
      }
    }
  },
  watch: {},
  created() {},
  mounted() {
    this.el = this.$refs['box']
    this.clock = new THREE.Clock()
    this.initThree()
  },
  activated() {},
  deactivated() {},
  updated() {},
  beforeDestroy() {
    if (this.animationFrameId) {
      cancelAnimationFrame(this.animationFrameId)
    }
    // 移除事件监听
    this.el.removeEventListener('mousemove', this.onMouseMove)
    this.el.removeEventListener('mouseleave', this.onMouseLeave)
  },
  destroyed() {},
  methods: {
    initThree() {
      this.initScene()
      this.initCamera()
      this.initRender()
      this.initLight()
      this.initControls()
      this.initRaycaster()
      this.animate()
      this.scene.add(this.setGridHelper(100 * 2, 10 * 2))
      this.scene.add(this.setAxesHelper(100000))

      this.drawMap()
      this.initEventListeners()
    },

    initRaycaster() {
      this.raycaster = new THREE.Raycaster()
      this.mouse = new THREE.Vector2()
    },

    initEventListeners() {
      this.el.addEventListener('mousemove', this.onMouseMove)
      this.el.addEventListener('mouseleave', this.onMouseLeave)
    },

    onMouseMove(event) {
      // 计算鼠标在归一化设备坐标中的位置 (-1 到 +1)
      const rect = this.el.getBoundingClientRect()
      this.mouse.x = ((event.clientX - rect.left) / rect.width) * 2 - 1
      this.mouse.y = -((event.clientY - rect.top) / rect.height) * 2 + 1

      this.updateTooltip()
    },

    onMouseLeave() {
      this.hideTooltip()
    },

    updateTooltip() {
      // 更新射线
      this.raycaster.setFromCamera(this.mouse, this.camera)

      // 计算与地图对象的交点
      const intersects = this.raycaster.intersectObjects(this.mapMeshes)

      if (intersects.length > 0) {
        const intersect = intersects[0]
        const mesh = intersect.object

        // 获取区域名称或其他信息
        const areaName = mesh.userData.areaName || '未知区域'
        const center = mesh.userData.center || { x: 0, y: 0 }

        this.showTooltip(areaName, event.clientX, event.clientY)

        // 可以添加高亮效果
        this.highlightArea(mesh)
      } else {
        this.hideTooltip()
        this.clearHighlight()
      }
    },

    showTooltip(content, x, y) {
      this.tooltip.visible = true
      this.tooltip.content = content
      this.tooltip.x = x
      this.tooltip.y = y
    },

    hideTooltip() {
      this.tooltip.visible = false
      this.tooltip.content = ''
    },

    highlightArea(mesh) {
      // 清除之前的高亮
      this.clearHighlight()

      // 设置高亮材质
      mesh.originalMaterial = mesh.material
      const highlightMaterial = new THREE.MeshBasicMaterial({
        color: '#ff6b6b',
        transparent: true,
        opacity: 0.8
      })
      mesh.material = highlightMaterial
      mesh.userData.isHighlighted = true
    },

    clearHighlight() {
      this.mapMeshes.forEach(mesh => {
        if (mesh.userData.isHighlighted && mesh.originalMaterial) {
          mesh.material = mesh.originalMaterial
          mesh.userData.isHighlighted = false
        }
      })
    },

    async drawMap() {
      const lineGroup = new THREE.Group()
      const exturdeGroup = new THREE.Group()
      const res = await this.getMapData()
      console.log('res', res)

      const regionCenter =
        (res.properties && res.properties.centroid) ||
        res.features[0]['properties']['center']
      this.projection = d3.geoMercator().center(regionCenter).translate([0, 0])

      res.features.slice(0).forEach((item, index) => {
        const coordinates = item.geometry.coordinates
        const properties = item.properties || {}
        const areaName = properties.name || `区域${index + 1}`

        coordinates.forEach(polygon => {
          if (polygon.length > 1) {
            polygon = [polygon]
          }

          polygon.forEach(p => {
            const lineObj = this.darwLine(p)
            const exturde = this.shapeToExturde(lineObj.shape)

            // 为拉伸模型添加用户数据
            exturde.userData = {
              areaName: areaName,
              center: this.calculatePolygonCenter(p),
              type: 'mapArea'
            }

            lineGroup.add(lineObj.mesh)
            exturdeGroup.add(exturde)

            // 添加到可交互的网格列表
            this.mapMeshes.push(exturde)
          })
        })
      })

      let scaleSize = this.getModelScaleValue(lineGroup, 100)
      lineGroup.scale.set(scaleSize, scaleSize, scaleSize)
      exturdeGroup.scale.set(scaleSize, scaleSize, 1)
      this.scene.add(lineGroup)
      this.scene.add(exturdeGroup)
    },

    calculatePolygonCenter(points) {
      // 简单计算多边形中心点
      let sumX = 0
      let sumY = 0

      points.forEach(point => {
        const [x, y] = this.projection(point)
        sumX += x
        sumY += -y // 注意Y坐标取负
      })

      return {
        x: sumX / points.length,
        y: sumY / points.length
      }
    },

    darwLine(pos) {
      const geo = new THREE.BufferGeometry()
      const shape = new THREE.Shape()
      const lineMaterial = new THREE.LineBasicMaterial({
        color: '#bb3'
      })

      for (let i = 0; i < pos.length; i++) {
        const [x, y] = this.projection(pos[i])
        if (i === 0) {
          shape.moveTo(x, -y)
        }
        shape.lineTo(x, -y)
      }

      const points = shape.getPoints()
      geo.setFromPoints(points)
      const mesh = new THREE.Line(geo, lineMaterial)
      return {
        shape,
        mesh
      }
    },

    shapeToExturde(shape) {
      const geometry = new THREE.ExtrudeGeometry(shape, this.extrudeOptions)
      const material1 = new THREE.MeshBasicMaterial({
        color: '#3192FF',
        transparent: true
      })
      const material2 = new THREE.MeshBasicMaterial({
        color: '#30DAFE',
        transparent: true,
        opacity: 0.8
      })
      const mesh = new THREE.Mesh(geometry, [material1, material2])
      return mesh
    },

    getModelScaleValue(obj, referenceVal = 10000) {
      const size = this.getModelSize(obj)
      const { x, y, z } = size
      const maxVal = Math.max(x, y, z)
      const scaleValue = referenceVal / maxVal
      return scaleValue
    },

    getModelSize(model) {
      const box3 = new THREE.Box3()
      box3.expandByObject(model)
      const size = new THREE.Vector3()
      box3.getSize(size)
      return size
    },

    getMapData() {
      return axios.get('/aq-geojson/湖北省.json').then(res => res.data)
    },

    setGridHelper(size, divisions) {
      const gridHelper = new THREE.GridHelper(size, divisions)
      gridHelper.material.opacity = 0.8
      gridHelper.material.transparent = true
      return gridHelper
    },

    setAxesHelper(size) {
      return new THREE.AxesHelper(size)
    },

    initScene() {
      this.scene = new THREE.Scene()
    },

    initCamera() {
      const asp = this.el.offsetWidth / this.el.offsetHeight
      this.camera = new THREE.PerspectiveCamera(45, asp, 0.1, 10000000)
      this.camera.position.set(300, 300, 300)
      this.camera.lookAt(this.scene.position)
      this.scene.add(this.camera)
    },

    initRender(clearColor = '#000') {
      const width = this.el.offsetWidth
      const height = this.el.offsetHeight
      this.renderer = new THREE.WebGLRenderer({
        antialias: true,
        alpha: true
      })
      this.renderer.setPixelRatio(window.devicePixelRatio)
      this.renderer.setSize(width, height)
      this.el.append(this.renderer.domElement)
    },

    initLight() {
      const ambientLight = new THREE.AmbientLight('#fff', 0.4)
      this.scene.add(ambientLight)
      const directionalLight = new THREE.DirectionalLight('#fff', 0.8)
      directionalLight.position.set(30, 30, 30).normalize()
      this.scene.add(directionalLight)
    },

    initControls() {
      this.controls = new OrbitControls(
        this.camera,
        this.renderer.domElement,
        {}
      )
      this.controls.enableDamping = true
      this.controls.dampingFactor = 0.05
    },

    render() {
      const dt = this.clock.getDelta()
      const T = clock.getDelta()
      timeS = timeS + T
      if (timeS > renderT) {
        this.controls.update(dt)
        this.renderer.render(this.scene, this.camera)
        timeS = 0
      }
    },

    animate() {
      this.render()
      this.animationFrameId = requestAnimationFrame(this.animate)
    }
  },
  filters: {}
}
</script>

<style scoped lang="scss">
.three-wrapper {
  height: 100%;
  position: relative;
  .box {
    height: 100%;
    width: 100%;
    background: url(./images/map-bg.png);
    background-size: cover;
    background-repeat: no-repeat;
    overflow: hidden;
    cursor: pointer;
  }
  .actions {
    position: absolute;
    bottom: 10px;
    left: 10px;
    display: flex;
    gap: 10px;

    button {
      padding: 8px 16px;
      border: none;
      background-color: #409eff;
      color: #fff;
      border-radius: 6px;
      cursor: pointer;
      font-size: 14px;
      transition: all 0.3s ease;

      &:hover {
        background-color: #66b1ff;
        transform: translateY(-2px);
        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
      }
    }
  }

  .tooltip {
    position: fixed;
    background: rgba(0, 0, 0, 0.8);
    color: white;
    padding: 8px 12px;
    border-radius: 4px;
    font-size: 14px;
    pointer-events: none;
    z-index: 1000;
    max-width: 200px;
    word-wrap: break-word;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);

    &::after {
      content: '';
      position: absolute;
      top: -5px;
      left: 10px;
      width: 0;
      height: 0;
      border-left: 5px solid transparent;
      border-right: 5px solid transparent;
      border-bottom: 5px solid rgba(0, 0, 0, 0.8);
    }
  }
}
</style>
